package com.ssy.lingxi.platform.manage.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.entity.base.AppDownloadLink;
import com.ssy.lingxi.platform.manage.model.request.appdownloadlink.AppDownloadLinkRequest;
import com.ssy.lingxi.platform.manage.repository.AppDownloadLinkRepository;
import com.ssy.lingxi.platform.manage.service.IAppDownloadLinkService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @menu 平台后台 - 系统设置 - APP链接设置 - 业务实现层
 * @author fhj
 * @version 2.0.0
 * @date 2021/04/07
 */
@Service
public class AppDownloadLinkServiceImpl implements IAppDownloadLinkService {

    @Resource
    private AppDownloadLinkRepository appDownloadLinkRepository;

    @Override
    public Wrapper<List<AppDownloadLink>> find(Integer status) {
        //获取所有
        List<AppDownloadLink> list = appDownloadLinkRepository.findAll();

        //如果获取不到数据，需要初始化
        if(CollectionUtil.isEmpty(list)) {
            AppDownloadLink ios = new AppDownloadLink();
            AppDownloadLink android = new AppDownloadLink();
            ios.setId(1L);
            ios.setTitle(1);
            android.setId(2L);
            android.setTitle(2);
            list.add(ios);
            list.add(android);
            appDownloadLinkRepository.saveAll(list);
        }

        //通过状态值参数进行筛选
        if(status != null) {
            list = list.stream().filter(a -> a.getStatus().equals(status)).collect(Collectors.toList());
        }

        return Wrapper.success(list);
    }

    @Override
    @Transactional
    public Wrapper<Void> update(AppDownloadLinkRequest request) {
        AppDownloadLink appDownloadLink = appDownloadLinkRepository.findById(request.getId()).orElse(null);
        if(appDownloadLink != null) {
            appDownloadLink.setLink(request.getLink());
            appDownloadLink.setStatus(request.getStatus());
            appDownloadLinkRepository.saveAndFlush(appDownloadLink);
        }
        return Wrapper.success();
    }
}
